package com.meida.zsd.app.listener;

import com.alibaba.fastjson.util.TypeUtils;
import com.meida.module.order.provider.service.OrderInfoService;
import com.meida.module.system.provider.service.SysExpireStrategyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@Slf4j
public class RedisKeyExpireListener extends KeyExpirationEventMessageListener {


    @Autowired
    private SysExpireStrategyService sysExpireStrategyService;

    @Autowired
    private OrderInfoService orderInfoService;

    public RedisKeyExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String redisKey = new String(message.getBody());
        String key = new String(message.getBody());
        log.info("redis过期key监听" + key);
        String prefix = "unpaidOrder";
        if (key.contains(prefix)) {
            Long orderId = TypeUtils.castToLong(key.split(":")[1]);
            if (orderInfoService.getById(orderId).getPayState() == 0) {
                orderInfoService.closeOrder(new HashMap() {{
                    put("orderId", orderId);
                }});
                sysExpireStrategyService.deleteByRedisKey(redisKey);
            }


        }

    }
}
